unit LingrProcedure;


(*
 *   Copyright (c) 2008 Shintaro Akiyama (freeandnil.self@gmail.com)
 *
 *   Redistribution and use in source and binary forms, with or without
 *   modification, are permitted provided that the following conditions
 *   are met:
 *
 *   1. Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *   2. Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *
 *   3. Neither the name of the authors nor the names of its contributors
 *      may be used to endorse or promote products derived from this
 *      software without specific prior written permission.
 *
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 *   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 *   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 *   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 *   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *)


interface

uses Classes, SysUtils, LingrRequest, LingrResponse;

type
  ELingrError = class(Exception);

  TLingrProcedure = class
  private
    FUrl: string;
    FOutput: TStrings;
  public
    constructor Create;
    procedure CallPost(const Method: String; const Req: TLingrRequest;
       Ret: TLingrResponse);
    procedure CallGet(const Method: String; const Req: TLingrRequest;
        Ret: TLingrResponse);
    procedure SetDebugOutput(Strings: TStrings);
    property Url: string read FUrl write FUrl;
  end;

  function LingrProc: TLingrProcedure;  // singleton metthod

implementation

uses httpsend;

var
  LingrProcSingleton: TLingrProcedure;

function LingrProc: TLingrProcedure;
begin
  Result := LingrProcSingleton;
end;

procedure CheckError(Http: THTTPSend);
begin
  if Http.ResultCode <> 200 then
    raise ELingrError.CreateFmt('Error Code: %d' + sLineBreak + '%s', [Http.ResultCode, Http.ResultString]);
end;


{ TLingrConnection }

constructor TLingrProcedure.Create;
begin
  FOUtput := nil;
end;

procedure TLingrProcedure.CallGet(const Method: String;
  const Req: TLingrRequest; Ret: TLingrResponse);
var
  data: string;
  Buf: string;
  TS: TStringStream;
  Http: THTTPSend;
begin
  TS := TStringStream.Create(Buf);
  try
    if Req <> nil then begin
      Data := UTF8Encode(Req.Catenate);
      if FOutput <> nil then begin
        FOutput.Add('GET ' + Method);
        FOutput.Add(Data);
      end;
    end;
    Http := THTTPSend.Create;
    try
      if Http.HTTPMethod('GET', FURL + Method + '?' + Data) then
        TS.CopyFrom(Http.Document, 0);
      Ret.SetResponse(TS.DataString);
      CheckError(Http);
      if not Ret.IsOK then
        raise ELingrError.CreateFmt('%s', [TS.DataString]);
    finally
      HTTP.Free;
    end;
  finally
    TS.Free;
  end;
end;

procedure TLingrProcedure.CallPost(const Method: String;
  const Req: TLingrRequest; Ret: TLingrResponse);
var
  Data: string;
  Buf: string;
  TS: TStringStream;
  Http: THTTPSend;
begin
  TS := TStringStream.Create(Buf);
  try
    if Req <> nil then begin
      Data := UTF8Encode(Req.Catenate);
      if FOutput <> nil then begin
        FOutput.Add('POST ' + Method);
        FOutput.Add(Data);
      end;
    end;
    Http := THTTPSend.Create;
    try
      Http.Document.Write(PChar(Data)^, Length(Data));
      HTTP.MimeType := 'application/x-www-form-urlencoded';
      if Http.HTTPMethod('POST', FURL + Method) then
        TS.CopyFrom(HTTP.Document, 0);
      if FOutput <> nil then FOutput.Add(TS.DataString);
      CheckError(Http);
      Ret.SetResponse(TS.DataString);
      if not Ret.IsOK then
        raise ELingrError.CreateFmt('%s', [TS.DataString]);
    finally
      Http.Free;
    end;
  finally
    TS.Free;
  end;
end;

procedure TLingrProcedure.SetDebugOutput(Strings: TStrings);
begin
  FOutput := Strings;
end;

initialization
  LingrProcSingleton := TLingrProcedure.Create;

finalization
  LingrProcSingleton.Free;
end.
